import { createModel } from "./modelFactory.js";

function doNext(vm, args) {
  const { ns, name, action, data } = args;
  vm.utils.http_post("/meta-models/batch-do", { ns, name, action, data }, x => {
    if (x.code == '200') {
      alert(x.message);
    }
    vm.reLoad();
  });
}

function doOpts(vm, cfg, args) {
  const { method } = args.meta;
  const moduleName = args.meta.model || "~";
  const model = vm.getModel(moduleName);
  if (model == null) {
    alert("未定义数据模型'" + moduleName + "'，无法执行！");
    return;
  }
  const { ns, module } = model;

  let rows = null;
  if (cfg.selRows) {
    rows = model.exec("selRows");
  } else {
    rows = [];
  }

  args.data = args.data || {};
  args.param = args.param || {};
  args.ns = ns;
  args.name = module;
  args.action = method;
  args.data.rows = rows;
  new Promise(function (resolve, reject) {
    args.promise = {
      resolve, reject
    }
  }).then(() => {
    doNext(vm, args);
  }).catch((args) => {
    console.log("Canceled!");
  });

  if (method) {
    console.log("exec:'" + method + "'");
    let result = vm.execute(method, args);
    if (result == null || result == true) {
      doNext(vm, args);
    }
  } else {
    alert("batchDo/do方法，需要设置'method'属性，以确定后绪方法");
  }
}

export default function (meta, vm) {
  vm.models = createModel(vm);

  return {
    onInit: function () {
      vm.on("do", (args) => {
        doOpts(vm, {
          "selRows": false
        }, args);
      });

      vm.on("batchDo", (args) => {
        doOpts(vm, {
          "selRows": true
        }, args);
      });

      /**
       * 
       */
      vm.on("list", param => {
        const gridModel = vm.getModel(param?.name);
        if (!gridModel) {
          throw "未定义数据模型！";
        }
        const args = {
          "ns": gridModel.ns,
          "name": gridModel.name,
          "data": {
            "pageSize": gridModel.pageSize || 10,
            "pageIndex": gridModel.pageIndex || 1,
            "condition": gridModel.condition || [],
            "orders": gridModel.orders
          }
        }
        let br = vm.execBefore("list", args);
        if (br == null || br == true) {
          vm.utils.dispatch("/meta-models/list", args, rs => {
            vm.setData(args.alias, rs.data);
          });
        }
      });

      /**
       * 加载明细数据
       */
      vm.on("detail", param => {
        const dataModel = vm.getModel(param?.name);
        if (!dataModel) {
          throw "未定义数据模型！";
        }
        const { params } = vm;
        let data = {

        };
        if (params) {
          for (var key in params) {
            if (key == 'mode') {
              continue;
            }
            data[key] = params[key];
          }
        }

        const args = {
          "ns": dataModel.ns,
          "name": dataModel.name,
          data
        };
        vm.utils.dispatch("/meta-models/detail", args, rs => {
          vm.setData(args.alias, rs.data);
        });
      });

      vm.on("add", param => {
        const dataModel = vm.getModel(param?.name);
        if (!dataModel) {
          throw "未定义数据模型！";
        }
        const { params } = vm;
        let data = {

        };
        if (params) {
          for (var key in params) {
            if (key == 'mode') {
              continue;
            }
            data[key] = params[key];
          }
        }

        const args = {
          "ns": dataModel.ns,
          "name": dataModel.name,
          data
        };
        vm.utils.dispatch("/meta-models/add", args, rs => {
          vm.setData(args.alias, rs.data);
          vm.setMode("add");
        });
      });

      vm.on("create", param => {
        vm.openDetail({ "mode": "add" });
      });

      vm.on("delete", param => {
        if (param.data.rows && param.data.rows.length > 0) {
          if (confirm("将要删除【" + param.data.rows.length + "】个数据对象，\r\n是否继续?")) {
            return true;
          } else {
            return false;
          }
        } else {
          alert("未选择数据行！");
          return false;
        }

      });

      vm.on("save", param => {
        const dataModel = vm.getModel(param?.model);
        if (!dataModel) {
          vm.utils.message("未找到数据模型定义！'model' = " + param?.model);
          return;
        }
        const reqData = {
          "ns": dataModel.ns,
          "name": dataModel.name,
          "data": {
            "rows": [dataModel.exec("getData")],
            "param": {

            }
          }
        }
        vm.utils.dispatch("/meta-models/save", reqData, rs => {
          param.result = rs.data;
          if (param.callback) {
            param.callback(param);
          }
        });
      });
    }
  }
}